﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using SportStore.Models.Concrete;
using SportStore.Models.Abstract;
using SportStore.Models.Entities;
using SportStore.Models;
using System.Threading;

namespace SportStore.Controllers
{
    public class CartController : Controller
    {
        private IProductRepository repository = new EFProductRepository();
        private IOrderProcessor orderProcessor = new EmailOrderProcessor();


        public void AddToCart(Cart cart,int productId,int quantity)
        {
             Product product = repository.Products.FirstOrDefault(p => p.ProductID == productId);
            if (product != null) cart.AddItem(product, quantity);
            //return PartialView("Summary",cart);
        }

        public ViewResult RemoveFromCart(Cart cart, int productId, string returnUrl)
        {
            Product product = repository.Products.FirstOrDefault(p => p.ProductID == productId);

            if (product != null) cart.RemoveLine(product);
            return View("Index", new CartIndexViewModel { Cart = cart, ReturnUrl = returnUrl });
        }

        public ViewResult Summary(Cart cart)
        {
            return View(cart);
        }

        public ActionResult Index(Cart cart, string returnUrl="/")
        {
            string part2="";
            try
            {
                part2 = returnUrl.Split('#')[1];
            }
            catch {
                part2 = "";
            }
            return View(new CartIndexViewModel { Cart = cart, ReturnUrl = part2 });
        }

        public ViewResult Checkout()
        {
            return View(new ShippingDetails());
        }

        [HttpPost]
        public ViewResult Checkout(Cart cart, ShippingDetails shippingDetails)
        {
            if (cart.Lines.Count() == 0)
            {
                ModelState.AddModelError("", "Sorry your cart is empty");
            }

            if (ModelState.IsValid)
            {
                orderProcessor.ProcessOrder(cart, shippingDetails);
                cart.Clear();
                return View("Completed");
            }
            else return View(shippingDetails);
        }

    }
}
